/**
 *	流程模块接口
 *	开发者：雨中磐石
 *	地址：www.rockoa.com
 *	日期：2023-07-19
 */

package com.framework.Module.REIM.immess;




import com.framerock.db.DB;
import com.framerock.db.DBWhere;
import com.framerock.server.Response;
import com.framerock.baselib.CDate;
import com.framerock.baselib.Jiami;
import com.framerock.baselib.Json;
import com.framerock.baselib.Rock;
import com.framework.Chajian.ChajianReim;
import com.framework.ACore.Model;
import com.framework.Flow.FlowListener;
import com.framework.Model.ModelCompany;
import com.framework.Model.ModelReim;
import com.framework.Model.ModelUsera;

import java.util.ArrayList;
import java.util.Map;


public class FlowListenerimmess extends FlowListener {




    @Override
    public String onAction(String act, String params) {
        if(act.equals("sendchat"))return this.sendchat();
        if(act.equals("chatdata"))return this.chatdata();
        if(act.equals("creategroup"))return this.creategroup();
        if(act.equals("cehui"))return this.cehui();
        if(act.equals("delmess"))this.delmess();
        return super.onAction(act, params);
    }

    //发送消息
    private String sendchat(){
        Json json = new Json();
        int receid   = mRequest.getInt("receid");
        int type     = mRequest.getInt("type");
        String atid     = mRequest.post("atid","0");
        String fileid   = mRequest.post("fileid");
        String cont     = mRequest.post("cont");
        String optdt    = mRequest.post("optdt");
        String nopush   = mRequest.post("nopush");
        String sendid   = "0",str,aid = mRequest.USEAID;
        if(Rock.isEmpt(optdt))optdt = CDate.now();
        Map<String,String> da = Rock.getMap(),info = null,ida,rs;
        ModelReim reimobj = new ModelReim(this.nDb);

        if(type == 0){
            info  = ModelUsera.get(this.nDb).getXinxi(receid+"");
        }
        if(type == 1){
            info  = reimobj.groupInfo(receid);
            int to= mFlow.getModel("imgroupuser").getCount("`type`="+type+" AND `gid`="+receid+" AND `sid`="+aid+"");
            if(to==0)return Response.returnError("你不在此群里无法发消息");
        }

        if(info==null)return Response.returnError("接收对象不存在");

        da.put("type", type+"");
        da.put("receid", receid+"");
        da.put("cont", cont);
        da.put("fileid", fileid);
        da.put("uid", mRequest.USERID);
        da.put("optdt", optdt);
        da.put("atid", atid);
        if(type==0 || type==1){
            if(!mRequest.USERABOOL)return Response.returnError("无效单位人员");
            da.put("sendid", aid);
            da.put("cid", mRequest.COMPANYID);
        }
        int id = mFlow.mModel.insert(da);

        json.putVal("optdt", optdt);
        json.putInt("id", id);
        json.putVal("fileid", fileid);
        json.putVal("nuid", mRequest.post("nuid"));

        String arr[] = optdt.split(" "),lastcont = Jiami.base64decode(cont);
        int laid    = lastcont.length();
        lastcont    = lastcont.substring(0, (laid>50) ? 50 : laid);
        if(type==1)lastcont = ""+mRequest.USEANAME+":"+lastcont+"";
        lastcont    = Jiami.base64encode(lastcont);

        String idaa[]= new String[]{
                "type", type+"",
                "optdt",optdt,
                "lastcont", lastcont,
                "lastid", id+"",
                "cid", mRequest.COMPANYID
        };


        //REIM推送
        String uids = "",uid,title="",mess="",icon = "",xxid = receid+"",receids = "";
        if(type == 0){
            uid   = Rock.getMapString(info, "uid", "0");
            if(!uid.equals("0"))uids = ",p"+uid+",r"+uid+",m"+uid+"";
            title = mRequest.USEANAME;
            mess  = "发来一条消息("+arr[1]+")";
            icon  = mRequest.getLoginrs("face");
            xxid  = aid;

            //保存imhistory
            ida = Rock.getMap(idaa);
            ida.put("receid", receid+"");
            ida.put("sendid", aid);
            reimobj.addHistory(ida);

            ida = Rock.getMap(idaa);
            ida.put("receid", aid);
            ida.put("sendid", receid+"");
            ida.put("stotal", "0");
            reimobj.addHistory(ida);
            receids = ","+aid+","+receid+"";
        }

        if(type==1){
            String sql = "SELECT b.`uid`,b.`id` FROM `"+ DB.chuliPerfix("imgroupuser")+"` a LEFT JOIN `"+ DB.chuliPerfix("usera")+"` b ON a.`sid`=b.`id` WHERE a.`type`=1 AND a.`gid`="+receid+"";
            ArrayList<Map<String, String>> urows = this.nDb.getAll(sql);
            if(urows != null)for(int i=0; i<urows.size(); i++){
                rs  = urows.get(i);
                str = rs.get("id");
                ida = Rock.getMap(idaa);
                ida.put("receid", str);
                ida.put("sendid", receid+"");
                if(str.equals(aid))ida.put("stotal", "0");
                reimobj.addHistory(ida);
                uid   = Rock.getMapString(rs, "uid", "0");
                if(!uid.equals("0")){
                    uids += ",p"+uid+",r"+uid+",m"+uid+"";
                }
                receids += ","+rs.get("id")+"";
            }
            title   = info.get("name");
            icon    = info.get("face");
            mess    = "人员“"+mRequest.USEANAME+"”发来一条消息";
        }


        if(!Rock.isEmpt(uids) && !nopush.equals("1")){
            if(Rock.isEmpt(icon))icon = "images/noface.png";
            ChajianReim.obj(this.nDb).push(Rock.getMap(new String[]{
                    "type","chat",
                    "receid", uids.substring(1),
                    "title", title,
                    "xxtype", type+"",
                    "xxid",xxid,
                    "atid",atid,
                    "xtype", "send",//send,chehui
                    "mess", mess,
                    "messid", id+"",
                    "cnum", mRequest.getCompanyrs("num"),
                    "sendid", mRequest.USERID,//平台
                    "icon",icon,
            }));
        }
        if(!Rock.isEmpt(receids)){
            receids = receids.substring(1);
            mFlow.mModel.update("`receids`='"+receids+"'", id+"");
        }

        return json.getJson();
    }

    //数据
    private String chatdata(){
        int receid   = mRequest.getInt("receid");
        int minid    = mRequest.getInt("minid");
        int type     = mRequest.getInt("type"); //0单位人员，1单位组,2平台人员,3平台组
        int loadci   = mRequest.LOADCI,systotal,to,issend = 1;
        ArrayList<Map<String, String>> data = null,filearr = null;
        Map<String,String> receinfo = null,sendinfo = null,rs,srs;
        String maxid = mRequest.get("maxid");
        String aid   = mRequest.USEAID,showmsg = "",cid = mRequest.COMPANYID,str,fileids="";

        ModelCompany cModel = ModelCompany.get(this.nDb);
        ModelReim reimobj   = new ModelReim(this.nDb);

        if(loadci == 1) {
            if (type == 0) {
                receinfo = cModel.companyUsero(cid, receid + "");
                sendinfo = cModel.companyUsero(cid, aid);
            }
            if (type == 1) {
                receinfo = reimobj.groupInfo(receid);
                sendinfo = cModel.companyUsero(cid, aid);
                to = mFlow.getModel("imgroupuser").getCount(
                        new DBWhere()
                                .winto("type", 1)
                                .wint("gid", receid)
                                .wint("sid", aid)
                );
                if(to==0){
                    showmsg = "--你不在此群里--";
                    issend  = 0;
                }
            }
        }

        String where   = "`type`="+type+"",sendid,order = "`id` DESC",sendname,sendface;
        if(type == 0){
            sendid = aid;
            where += " AND ((`receid`="+receid+" AND `sendid`="+sendid+") OR (`receid`="+sendid+" AND `sendid`="+receid+"))";
            ModelReim.get(this.nDb).yiduHistory(type, sendid, receid);//标已读
            where += " AND "+DB.dbInstr("`receids`", sendid)+"";
        }
        if(type == 1){
            sendid = aid;
            where += " AND `receid`="+receid+"";
            ModelReim.get(this.nDb).yiduHistory(type, sendid, receid);//标已读
            where += " AND "+DB.dbInstr("`receids`", sendid)+"";
        }



        if(minid>0){
            where+=" AND `id`<"+minid+"";
        }
        if(!Rock.isEmpt(maxid)){
            where+=" AND `id`>"+maxid+"";
        }

        if(loadci==1){
            order += " LIMIT 5";
        }else{
            order += " LIMIT 10";
        }
        systotal= mFlow.mModel.getCount(where);
        data    = mFlow.mModel.getAll(where, "id,cont,optdt,sendid,fileid", order);
        if(data != null)for(int i=0;i<data.size();i++){
            systotal--;
            rs     = data.get(i);
            sendid = rs.get("sendid");
            sendname = "-";
            sendface = "images/noface.png";

            if(type == 0 || type==1){
                srs = cModel.companyUsero(cid, sendid);
                if(srs != null){
                    sendname = srs.get("name");
                    sendface = srs.get("face");
                    rs.put("deptname",srs.get("deptname"));
                    rs.put("ranking",srs.get("ranking"));
                }
            }
            rs.put("sendname",sendname);
            rs.put("sendface",sendface);

            str = rs.get("fileid");
            if(!str.equals("0"))fileids+=","+str+"";
        }

        if(!Rock.isEmpt(fileids)){
            filearr = mFlow.getModel("file").getAll("`fileid` IN("+fileids.substring(1)+")", "fileid,fileext,filename,filenum,thumbpath,filesize,filesizecn", "");
        }


        Json json       = new Json();
        json.putVal("receinfo", receinfo);
        json.putVal("sendinfo", sendinfo);
        json.putVal("data", data);
        json.putVal("showmsg", showmsg);
        json.putVal("filearr", filearr);
        json.putInt("loadci", loadci);
        json.putInt("systotal", systotal);
        json.putInt("issend", issend);
        json.putVal("servernow", CDate.now());

        return json.getJson();
    }

    //创建群
    private String creategroup(){
        String name = mRequest.post("name");
        Model obj   = mFlow.getModel("imgroup");
        String aid  = mRequest.USEAID,optdt = CDate.now();
        Map<String,String> da = Rock.getMap();
        da.put("name", name);
        da.put("type", "1");
        da.put("optdt", optdt);
        da.put("aid", aid);
        da.put("uid", mRequest.USERID);
        da.put("cid", mRequest.COMPANYID);
        int gid = obj.insert(da);
        ModelReim mobj = ModelReim.get(this.nDb);
        mobj.saveGroupUser(1, gid, aid, mRequest.COMPANYID);
        mobj.addHistory(Rock.getMap(new String[]{
                "type","1",
                "receid", aid,
                "sendid", gid+"",
                "optdt",optdt,
                "lastcont",Jiami.base64encode(""+mRequest.USEANAME+":创建了群"),
                "stotal","1",
                "cid", mRequest.COMPANYID
        }));
        return "";
    }


    //撤回
    private String cehui(){
        Json json       = new Json();
        String id      = mRequest.get("id");
        int type    = mRequest.getInt("type");
        int receid  = mRequest.getInt("receid");
        String optdt = CDate.now(),uids = "",uid;
        json.putVal("id", id);
        Map<String,String> da,rs = mFlow.mModel.getOne(id);
        String receids = rs.get("receids");
        String cid     = rs.get("cid");
        if(!Rock.isEmpt(receids)){
            if(type == 0 || type == 1){
                ArrayList<Map<String, String>> urows = mFlow.getModel("usera").getAll(new DBWhere()
                        .winto("cid", cid)
                        .wint("status", 1)
                        .wint("state", 1)
                        .win("id", receids)
                        .awhere("`uid`>0")
                        .show(), "uid", "");
                if(urows != null)for(int i=0;i<urows.size();i++){
                    da      = urows.get(i);
                    uid     = Rock.getMapString(da, "uid");
                    uids += ",p"+uid+",r"+uid+",a"+uid+"";
                }
            }
        }

        if(!Rock.isEmpt(uids)){
            ChajianReim.obj(this.nDb).push(Rock.getMap(new String[]{
                    "type","cehui",
                    "receid", uids.substring(1),
                    "messid", id,
                    "sendid", mRequest.USERID,//平台
            }));
        }
        mFlow.mModel.delete(id);
        mFlow.getModel("imhistory").update("`lastcont`='',`optdt`='"+optdt+"'", "`lastid`="+id+"");
        return json.getJson();
    }

    //删除消息
    private void delmess() {
        String id       = mRequest.get("id");
        int type        = mRequest.getInt("type");
        String aid      = "";
        if(type == 0 || type==1)aid = mRequest.USEAID;
        if(Rock.isEmpt(aid))return;
        Map<String,String> rs = mFlow.mModel.getOne(id);
        if(rs == null)return;
        String receids = rs.get("receids"),sid = "",sv1;
        if(Rock.isEmpt(receids))return;
        String arr[]    = receids.split(",");
        for(int i=0; i<arr.length; i++){
            sv1 = arr[i];
            if(!sv1.equals(aid)){
                sid+=","+sv1+"";
            }
        }
        if(!Rock.isEmpt(sid))sid = sid.substring(1);
        String optdt = CDate.now();
        if(Rock.isEmpt(sid)){
            mFlow.mModel.delete(id);
        }else {
            mFlow.mModel.update("`receids`='" + sid + "'", id);
        }
        mFlow.getModel("imhistory").update("`lastcont`='',`optdt`='"+optdt+"'", "`type`="+type+" AND `receid`="+aid+" AND `lastid`="+id+"");
    }
}
